// Copyright (C) 2021, Flickering Inc. All rights reserved.
// Author: haiquanchen (haiquanchen@flickering.ai)

const { ccclass, property } = cc._decorator;
@ccclass
export default class LightSweep extends cc.Component {
    @property({ type: Number, displayName: '扫光宽度' })
    wide: number = 0.02;
    @property({ type: Number, displayName: '扫光速度' })
    speed: number = 0.1;
    @property({ type: Number, displayName: '扫光亮度' })
    light: number = 1;
    @property({ type: Number, displayName: '循环时间段最小值' })
    rangeMin: number = 0;
    @property({ type: Number, displayName: '循环时间段最大值' })
    rangeMax: number = 1;

    private _time: number = 0.4;
    private _material: cc.MaterialVariant;

    onLoad() {
        // 获取材质
        if (this.node.getComponent(cc.Sprite)) {
            this._material = this.node.getComponent(cc.Sprite).getMaterial(0);
            this._material.setProperty('wide', this.wide);
            this._material.setProperty('light', this.light);
        }
    }

    update(dt) {
        if (this._material && this._material.name == 'light_sweep (Instance)') {
            if (this._time > 2) {
                this._time = 0.0;
            }

            this._material.setProperty('u_time', this._time);
            this._time += dt * this.speed;
        }
    }

    /**
     * 重置材质
     */
    public resetMaterial() {
        if (this.node.getComponent(cc.Sprite)) {
            this._material = this.node.getComponent(cc.Sprite).getMaterial(0);
            this._material.setProperty('wide', this.wide);
            this._material.setProperty('light', this.light);
        }
    }
}
